<template>
  <div>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 弹出添加用户框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 用户数据 -->
        <el-form
          :model="AddForm"
          :rules="Userules"
          ref="AddFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="AddForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="AddForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="AddForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="AddForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!--  修改对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <!-- 用户数据 -->
        <el-form
          :model="editForm"
          :rules="editrules"
          ref="EditFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="EditUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 弹出分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="fpDialogVisible"
        width="50%"
        @close="fpDialogColse"
      >
        <div>
          <p>当前用户名：{{fpForm.username}}</p>
          <p>当前角色名称： {{fpForm.role_name}}</p>
          <p>分配新角色:  <el-select v-model="Selectvalueid"
           placeholder="请选择">
                <el-option
                  v-for="item in Rolsevalue"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
        </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="fpDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="fpRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话号码"></el-table-column>
        <el-table-column prop="role_name" label="职称"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="RemoveUserByID(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="fpUserRolse(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[1, 3, 5, 7]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userlist: [],
      total: 0,
      // 控制用户添加按钮
      addDialogVisible: false,
      // 获取用户输入的数据
      AddForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 定义Form 的规则
      Userules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 8, message: '长度在6到8个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户值
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 编辑form的规则
      editrules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // { validate: 'checkEmail', trigger: 'blur' }
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { min: 8, max: 11, trigger: 'blur' }
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色确认框
      fpDialogVisible: false,
      // 分配角色查询到的用户信息
      fpForm: {},
      // 查寻到的角色列表信息
      Rolsevalue: [],
      // 已选中的id值
      Selectvalueid: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // 根据选择改变页面值
    handleCurrentChange(newsize) {
      this.queryInfo.pagenum = newsize
      this.getUserList()
    },
    // 监听switch 开关的状态改变
    async userStateChanged(userinfo) {
      // 能监听到 修改不了
      // console.log(userinfo)
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )

      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 添加用户弹出框 重置信息
    addDialogClose() {
      this.$refs.AddFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.AddFormRef.validate(async valid => {
        if (!valid) return
        // console.log(valid)
        // const { data: res } = await this.$http.post('users', this.AddForm)
        const { data: res } = await this.$http.post('users', this.AddForm)
        // console.log(res.data)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 根据修改对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户失败！')
      }
      // this.$message.success('获取用户成功！')
      this.editForm = res.data

      // console.log(id)
      this.editDialogVisible = true
    },
    // 修改按钮传数据
    EditUser() {
      this.$refs.EditFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
        this.$message.success('更新用户信息成功！')
        this.editDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 根据id删除数据
    async RemoveUserByID(id) {
      // this.detDialogVisible = true
      // 询问是否删除数据
      const confilmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '删除',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消删除',
          type: 'warning'
        }
      ).catch(err => err)
      if (confilmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户信息失败！')
      }
      this.$message.success('删除成功！')
      this.getUserList()
      // this.detDialogVisible = false
    },
    // 修改对话框重置
    editDialogClose() {
      this.$refs.EditFormRef.resetFields()
    },
    // 点击分配角色获取该用户的id值
    async fpUserRolse(roles) {
      this.fpForm = roles
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      // console.log(res.data)
      this.Rolsevalue = res.data
      this.fpDialogVisible = true
    },
    // 分配角色
    async fpRoles() {
      if (!this.Selectvalueid) {
        return this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put(`users/${this.roles.id}/role`, {
        // eslint-disable-next-line key-spacing
        rid : this.Selectvalueid
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.fpDialogVisible = false
    },
    // 重置对话框
    fpDialogColse() {
      this.Selectvalueid = ''
      this.Rolsevalue = {}
    }
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 25px;
}
</style>
